﻿using Ldt.InformationUnit.Common;
using LdtDataEngin.ModuleDetail.BaseModule.MultiFack;
using LdtDataEngin.ModuleDetail.BaseModule.Optimization;
using LdtDataEngin.ModuleDetail.CommonModule;
using LdtJudge.DataEngine.CallInterface.ConfiCenter;
using LdtJudge.DataEngine.Common;
using LdtJudge.DataEngine.Common.XmlUtility;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model.Dudection;
using LdtJudge.DataEngine.Model.EvidenceDerivation;
using LdtJudge.DataEngine.Model.XMLConfigModel.DataStores;
using LdtJudge.DataEngine.Model.XMLConfigModel.SameNodeConfigModel;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace LdtDataEngin.ModuleDetail.OptimizationModule.EvidenceDerivation
{
    public class EvidenceCorresponding : OptimizationBase
    {

        /// <summary>
        /// 进行证据与事实要素比对
        /// </summary>
        public EvidenceCorresponding(DataContext dataContext, string moduleName)
        {
            this.dataContext = dataContext;
            this.ModuleName = moduleName;
        }

        #region 案件类型添加
        /// <summary>
        /// 案件类型添加
        /// </summary>
        /// <param name="evidenceTypeConfigModel"></param>
        public void Corresponding(EvidenceTypeConfigModel evidenceTypeConfigModel)
        {
            //加载证据类型配置
            var evidenceCaseType = evidenceTypeConfigModel.evidenceCaseTypeList.FirstOrDefault(a => a.value == dataContext.DataLayerAns.CaseType);
            if (evidenceCaseType != null)
            {
                var evidenceType = evidenceCaseType.evidenceTypeList.FirstOrDefault(a => a.evidenceBookTypeList.FirstOrDefault(a => a.value.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower()) != null);
                if (evidenceType != null)
                {
                   
                    string path = evidenceType.evidenceBookTypeList.FirstOrDefault(a => a.value.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower()).path;
                    if (dataContext.DataLayerAns.AnalysisResultsDataModel != null && dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList.Count > 0)
                    {

                        List<string> pathList = path.Split(new string[] { "/@" }, StringSplitOptions.None).ToList();
                        if (pathList.Count == 2)
                        {
                            string xmlpath = pathList[0];
                            string attname = pathList[1];

                            DataModel evidencDataModel = XmlUtility.ConditionFirstOrDefaultDataModel(dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList, "", xmlpath);
                            if (evidencDataModel.AttributesList.FirstOrDefault(a => a.Name == attname) != null)
                            {
                                evidencDataModel.AttributesList.FirstOrDefault(a => a.Name == attname).sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue = evidenceType.value;
                            }
                            else
                            {
                                AttributeInfo attributeInfo = new AttributeInfo();
                                attributeInfo.Name = attname;
                                Source source = new Source();
                                source.SaveValue = evidenceType.value;
                                source.SourceCode = dataContext.DataLayerAns.SourceCode;
                                source.IsCheck = "1";
                                attributeInfo.sourceList = new List<Source>();
                                attributeInfo.sourceList.Add(source);
                            }
                        }
                    }
                }
            }

        }
        #endregion

        /// <summary>
        /// 实体与非实体关系对应
        /// 证据形态 1.实体证据 2.非实体证据
        /// </summary>
        /// <param name="evidenceNameConfig"></param>
        public void EvidenceName(EvidenceNameConfig evidenceNameConfig, string sourceCode, string evideid)
        {
            XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = dataContext };
            List<EvidenceCompareCondition> conditionList = new List<EvidenceCompareCondition>();
            #region 证据对应配置
            var configModel = dataContext.DataLayerSys.GetConfigModel(ModuleName);
            string message = configModel.ConfigDetail.FirstOrDefault(a => a.Code.ToLower() == "evidencecompareconfig")?.ConfigContent;
            if(!string.IsNullOrWhiteSpace(message))
            {
                SameEvidenceCompareConfig sameEvidCompareConfig = XmlUtility.DeserializeToObject<SameEvidenceCompareConfig>(message);
                var sameCaseTypeConfig = sameEvidCompareConfig.CaseTypes.FirstOrDefault(x => x.Value.ToLower() == dataContext.DataLayerAns.CaseType.ToLower());
                if (sameCaseTypeConfig != null)
                {
                    var sameDocTypeConfig = sameCaseTypeConfig.DocTypes.FirstOrDefault(x => x.Value.ToLower().Contains(sourceCode.ToLower()));
                    if (sameDocTypeConfig != null)
                        conditionList = sameDocTypeConfig.Conditions;
                }
            }
            else
            {
                dataContext.InteractiveShow.LogShow("实体证据与非实体证据比对配置不存在");
            }
            #endregion

            var evidenceCaseType = evidenceNameConfig.evidenceNameCaseTypeList.FirstOrDefault(a => a.value.ToLower() == dataContext.DataLayerAns.CaseType.ToLower());
            if (evidenceCaseType != null)
            {
                var eubstantialEviden = evidenceCaseType.eubstantialEvidenceList.FirstOrDefault(a => a.booktype.ToLower() == sourceCode.ToLower());
                if (eubstantialEviden != null)
                {
                    if (eubstantialEviden.evidenceModelList != null && eubstantialEviden.evidenceModelList.Count > 0)
                    {
                        List<DataModel> dataModelList = dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList;
                        List<string> xpathList = eubstantialEviden.path.Split(new string[] { "/@" }, StringSplitOptions.None).ToList();
                        if (xpathList != null && xpathList.Count == 2)
                        {
                            string attname = xpathList[1];
                            string xpath = xpathList[0];
                            List<DataModel> evdevcDataModelRootList = XmlUtility.ConditionDataModelList(dataContext.DataLayerOpt.SourdatModleList, "", xpath);
                            //查找所有非实体证据同时证据名称包含配置中名称的数据
                            if(evdevcDataModelRootList!=null && evdevcDataModelRootList.Any())
                            {
                                var sameEvids = evdevcDataModelRootList.Where(x => x.AttributesList.Any(a => a.Name == "证据形态"))
                                                                    .Where(x => x.AttributesList.FirstOrDefault(a => a.Name == "证据形态").sourceList.Any(s => s.IsCheck == "1" && s.SaveValue == "2"))
                                                                    .Where(x => x.AttributesList.Any(a => a.Name == "证据名称"))
                                                                    .Where(x => x.AttributesList.FirstOrDefault(a => a.Name == "证据名称").sourceList.Any(s => s.IsCheck == "1" && s.SaveValue.Contains(eubstantialEviden.name))).ToList();
                                var sameEvidss = evdevcDataModelRootList.Where(x => x.AttributesList.Any(a => a.Name == "证据名称"))
                                                                       .Where(x => x.AttributesList.FirstOrDefault(a => a.Name == "证据名称").sourceList.Any(s => s.IsCheck == "1" && s.SaveValue.Contains(eubstantialEviden.name)))
                                                                       .Where(x => !x.AttributesList.Any(a => a.Name == "证据形态") || (x.AttributesList.Any(a => a.Name == "证据形态") && x.AttributesList.FirstOrDefault(a => a.Name == "证据形态").sourceList.Any(s => s.IsCheck == "1" && s.SaveValue == "2"))).ToList();
                                if (sameEvids != null && sameEvids.Any())
                                {
                                    //获取实体证据数据
                                    var entityEvid = dataContext.DataLayerOpt.SourdatModleList.FirstOrDefault(x => x.ID == evideid);
                                    if (sameEvids.Count==1)
                                    {
                                        var entitySfid = entityEvid.AttributesList.FirstOrDefault(x => x.Name == "证据文件ID")?.sourceList?.FirstOrDefault(a => a.IsCheck == "1")?.SaveValue;
                                        if(!string.IsNullOrWhiteSpace(entitySfid))
                                            SetATTDataModel(sameEvids[0], "证据文件ID", entitySfid);
                                        var entityType = entityEvid.AttributesList.FirstOrDefault(x => x.Name == "证据类型")?.sourceList?.FirstOrDefault(a => a.IsCheck == "1")?.SaveValue;
                                        if(!string.IsNullOrWhiteSpace(entityType))
                                            SetATTDataModel(sameEvids[0], "证据类型", entityType);
                                        var entityClass = entityEvid.AttributesList.FirstOrDefault(x => x.Name == "证据分类")?.sourceList?.FirstOrDefault(a => a.IsCheck == "1")?.SaveValue;
                                        if (!string.IsNullOrWhiteSpace(entityClass))
                                            SetATTDataModel(sameEvids[0], "证据分类", entityClass);
                                        var entitySourceCode= entityEvid.AttributesList.FirstOrDefault(x => x.Name == "证据文书编号")?.sourceList?.FirstOrDefault(a => a.IsCheck == "1")?.SaveValue;
                                        if (!string.IsNullOrWhiteSpace(entitySourceCode))
                                            SetATTDataModel(sameEvids[0], "证据文书编号", entitySourceCode);
                                        var entitySourceName = entityEvid.AttributesList.FirstOrDefault(x => x.Name == "标准名称")?.sourceList?.FirstOrDefault(a => a.IsCheck == "1")?.SaveValue;
                                        if (!string.IsNullOrWhiteSpace(entitySourceName))
                                            SetATTDataModel(sameEvids[0], "标准名称", entitySourceName);
                                        //获取证据要素

                                        EvideDataElmentMerger(sameEvids[0], entityEvid);

                                        dataContext.DataLayerOpt.SourdatModleList.Remove(entityEvid);
                                    }
                                    else if (sameEvids.Count > 1)
                                    {
                                        #region 身份证旧逻辑
                                        ////按任娇要求，身份证的数据不调用推导，临时通过证据名称来匹配对应的非实体数据
                                        //var entityEvidName = entityEvid.AttributesList.FirstOrDefault(x => x.Name == "证据名称")?.sourceList?.FirstOrDefault(a => a.IsCheck == "1")?.SaveValue;
                                        //if (entityEvidName.Contains("身份证"))
                                        //{
                                        //    var personName = entityEvidName.Replace("身份证", "").Replace("居民", "").Replace("_", "");
                                        //    var unEntityData = sameEvids.Where(x => (x.AttributesList.FirstOrDefault(x => x.Name == "证据名称")?.sourceList?.FirstOrDefault(a => a.IsCheck == "1")?.SaveValue).Contains(personName)).FirstOrDefault();
                                        //    if (unEntityData != null)
                                        //    {
                                        //        var entitySfid = entityEvid.AttributesList.FirstOrDefault(x => x.Name == "证据文件ID")?.sourceList?.FirstOrDefault(a => a.IsCheck == "1")?.SaveValue;
                                        //        if (!string.IsNullOrWhiteSpace(entitySfid))
                                        //            SetATTDataModel(unEntityData, "证据文件ID", entitySfid);
                                        //        var entityType = entityEvid.AttributesList.FirstOrDefault(x => x.Name == "证据类型")?.sourceList?.FirstOrDefault(a => a.IsCheck == "1")?.SaveValue;
                                        //        if (!string.IsNullOrWhiteSpace(entityType))
                                        //            SetATTDataModel(unEntityData, "证据类型", entityType);
                                        //        var entityClass = entityEvid.AttributesList.FirstOrDefault(x => x.Name == "证据分类")?.sourceList?.FirstOrDefault(a => a.IsCheck == "1")?.SaveValue;
                                        //        if (!string.IsNullOrWhiteSpace(entityClass))
                                        //            SetATTDataModel(unEntityData, "证据分类", entityClass);
                                        //        var entitySourceCode = entityEvid.AttributesList.FirstOrDefault(x => x.Name == "证据文书编号")?.sourceList?.FirstOrDefault(a => a.IsCheck == "1")?.SaveValue;
                                        //        if (!string.IsNullOrWhiteSpace(entitySourceCode))
                                        //            SetATTDataModel(unEntityData, "证据文书编号", entitySourceCode);
                                        //        var entitySourceName = entityEvid.AttributesList.FirstOrDefault(x => x.Name == "标准名称")?.sourceList?.FirstOrDefault(a => a.IsCheck == "1")?.SaveValue;
                                        //        if (!string.IsNullOrWhiteSpace(entitySourceName))
                                        //            SetATTDataModel(unEntityData, "标准名称", entitySourceName);
                                        //        EvideDataElmentMerger(sameEvids[0], entityEvid);
                                        //        dataContext.DataLayerOpt.SourdatModleList.Remove(entityEvid);
                                        //    }
                                        //}
                                        #endregion
                                        //对应上多条数据，调用推导
                                        //Deduction(entityEvid);

                                        //获取实体证据的子级数据
                                        var entityDatas = xmlUtilCommon.SubordinateDataModelList(dataContext.DataLayerOpt.SourdatModleList, entityEvid);
                                        foreach (var item in sameEvids)
                                        {
                                            //获取非实体证据的子级数据
                                            var noEntityDatas = xmlUtilCommon.SubordinateDataModelList(dataContext.DataLayerOpt.SourdatModleList, item);
                                            bool isSame = EvidenceCompareByCondition(entityDatas, noEntityDatas, conditionList);
                                            if (isSame)
                                            {
                                                var entitySfid = entityEvid.AttributesList.FirstOrDefault(x => x.Name == "证据文件ID")?.sourceList?.FirstOrDefault(a => a.IsCheck == "1")?.SaveValue;
                                                if (!string.IsNullOrWhiteSpace(entitySfid))
                                                    SetATTDataModel(item, "证据文件ID", entitySfid);
                                                var entityType = entityEvid.AttributesList.FirstOrDefault(x => x.Name == "证据类型")?.sourceList?.FirstOrDefault(a => a.IsCheck == "1")?.SaveValue;
                                                if (!string.IsNullOrWhiteSpace(entityType))
                                                    SetATTDataModel(item, "证据类型", entityType);
                                                var entityClass = entityEvid.AttributesList.FirstOrDefault(x => x.Name == "证据分类")?.sourceList?.FirstOrDefault(a => a.IsCheck == "1")?.SaveValue;
                                                if (!string.IsNullOrWhiteSpace(entityClass))
                                                    SetATTDataModel(item, "证据分类", entityClass);
                                                var entitySourceCode = entityEvid.AttributesList.FirstOrDefault(x => x.Name == "证据文书编号")?.sourceList?.FirstOrDefault(a => a.IsCheck == "1")?.SaveValue;
                                                if (!string.IsNullOrWhiteSpace(entitySourceCode))
                                                    SetATTDataModel(item, "证据文书编号", entitySourceCode);
                                                var entitySourceName = entityEvid.AttributesList.FirstOrDefault(x => x.Name == "标准名称")?.sourceList?.FirstOrDefault(a => a.IsCheck == "1")?.SaveValue;
                                                if (!string.IsNullOrWhiteSpace(entitySourceName))
                                                    SetATTDataModel(item, "标准名称", entitySourceName);
                                                //获取证据要素
                                                EvideDataElmentMerger(item, entityEvid);
                                                dataContext.DataLayerOpt.SourdatModleList.Remove(entityEvid);
                                            }
                                        }
                                    }
                                }
                            }
                            #region 旧处理逻辑
                            //DataModel evdevcDataModelRoot = evdevcDataModelRootList.FirstOrDefault(a => a.ID != evideid);
                            //if (evdevcDataModelRoot.AttributesList.FirstOrDefault(a => a.Name == attname) != null)
                            //{
                            //    string evidName = evdevcDataModelRoot.AttributesList.FirstOrDefault(a => a.Name == attname).sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
                            //    var eviden = eubstantialEviden.evidenceModelList[0];
                            //    List<string> evidenPathList = eviden.path.Split(new string[] { "/@" }, StringSplitOptions.None).ToList();
                            //    if (evidenPathList.Count == 2)
                            //    {
                            //        string evxpath = evidenPathList[0];
                            //        if (evxpath.StartsWith("/"))
                            //        {
                            //            evxpath = evxpath.TrimStart('/');
                            //        }
                            //        List<DataModel> evidenList = XmlUtility.ConditionDataModelList(dataContext.DataLayerOpt.SourdatModleList, "", evxpath);
                            //        //获取非实体证据数据
                            //        evidenList = evidenList.Where(a => a.AttributesList.FirstOrDefault(b => b.Name == attname).sourceList.FirstOrDefault(f => f.IsCheck == "1" && f.SaveValue == evidName) != null)
                            //                               .Where(a => a.AttributesList.FirstOrDefault(b => b.Name == "证据形态") != null && a.AttributesList.FirstOrDefault(b => b.Name == "证据形态").sourceList.FirstOrDefault(f => f.IsCheck == "1" && f.SaveValue == "2") != null)
                            //                               .ToList();
                            //        if (evidenList == null || evidenList.Count == 0)
                            //        {
                            //            //没有对应上的数据
                            //        }
                            //        else if (evidenList.Count == 1)
                            //        {
                            //            //对应上一条数据
                            //            var entityData = dataContext.DataLayerOpt.SourdatModleList.FirstOrDefault(x => x.ID == evideid);
                            //            var entitySfid = entityData.AttributesList.FirstOrDefault(x => x.Name == "证据文件ID").sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
                            //            SetATTDataModel(evidenList[0], "文书ID", entitySfid);
                            //            var entityType = entityData.AttributesList.FirstOrDefault(x => x.Name == "证据类型").sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
                            //            SetATTDataModel(evidenList[0], "证据类型", entityType);
                            //            var entityClass = entityData.AttributesList.FirstOrDefault(x => x.Name == "证据分类").sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
                            //            SetATTDataModel(evidenList[0], "证据分类", entityClass);
                            //        }
                            //        else
                            //        {
                            //            //对应上多条数据
                            //            Deduction();

                            //        }
                            //    }
                            //}
                            #endregion
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 实体证据与非实体证据通过配置的条件进行比对
        /// </summary>
        /// <param name="entityDatas">实体证据数据</param>
        /// <param name="noEntityDatas">非实体证据数据</param>
        /// <param name="conditions">配置条件</param>
        /// <returns></returns>
        private bool EvidenceCompareByCondition(List<DataModel>entityDatas,List<DataModel>noEntityDatas,List<EvidenceCompareCondition> conditions)
        {
            bool isSame = false;
            if(conditions!=null && conditions.Any())
            {
                foreach (var conditionItem in conditions)
                {
                    var pathNames = conditionItem.ComparePath.Replace("\\", "/").Split('/', StringSplitOptions.RemoveEmptyEntries);
                    string conditionPath = string.Join("/", pathNames.Take(pathNames.Length - 1));
                    string attrName = pathNames.LastOrDefault().Replace("@", "");
                    var entityData = entityDatas.FirstOrDefault(x => x.XmlPath == conditionPath);
                    if(entityData!=null)
                    {
                        var entityValue=entityData.AttributesList.FirstOrDefault(x => x.Name == attrName)?.sourceList?.FirstOrDefault(a => a.IsCheck == "1")?.SaveValue;
                        var noEntityData= noEntityDatas.FirstOrDefault(x => x.XmlPath == conditionPath);
                        string noEntityValue = string.Empty;
                        if(noEntityData!=null)
                        {
                            noEntityValue=noEntityData.AttributesList.FirstOrDefault(x => x.Name == attrName)?.sourceList?.FirstOrDefault(a => a.IsCheck == "1")?.SaveValue;
                            if(entityValue==noEntityValue)
                            {
                                if(conditionItem.Conditions!=null && conditionItem.Conditions.Any())
                                {
                                    bool subCompareResult = EvidenceCompareByCondition(entityDatas, noEntityDatas, conditionItem.Conditions);
                                    if (subCompareResult)
                                        isSame = true;
                                }
                            }
                        }
                    }
                    if (isSame)
                        return true;
                }
            }
            return isSame;
        }

        /// <summary>
        /// 证据要素合并
        /// </summary>
        /// <param name="dataModelEvide"></param>
        /// <param name="dataModeEvideHs"></param>
        public void EvideDataElmentMerger(DataModel dataModelEvide,DataModel dataModeEvideHs) 
        {
            try
            {
                XmlNode evidexml;
                XmlNode evidehsxml;
                string evid= EvidElment(dataModelEvide, out evidexml);
                EvidElment(dataModeEvideHs, out evidehsxml);
                string strxmlTemplate = dataContext.DataLayerOpt.CaseCausesList[0].ElementXML;
                XmlDocument xmlDocumentTemplate = new XmlDocument();
                xmlDocumentTemplate.LoadXml(strxmlTemplate);
                XmlNode nodetemplate = xmlDocumentTemplate.SelectSingleNode("//事实要素");

                var sameNodeConfig = GetSameNodeConfig();
                List<SameNodeXml> opconfigList = sameNodeConfig?.xmllable?.ToList();
                MultiFactUnion multiFactunion = new MultiFactUnion() { dataContext = base.dataContext };


                XmlDocument confirmdocumenttemp = new XmlDocument();
                confirmdocumenttemp.LoadXml(string.Format("<{0}></{0}>", nodetemplate.ParentNode.Name));
                XmlNode nodeOut = confirmdocumenttemp.CreateElement("事实要素");
                confirmdocumenttemp.DocumentElement.AppendChild(nodeOut);
                if (evidexml!=null && evidehsxml!=null)
                {
                    // confirmdocumenttemp = evidehsxml;
                    multiFactunion.MultiFactUnionXml(nodetemplate, evidehsxml, evidexml, opconfigList, nodeOut, MultiFactBase.SameNodeHandleType.b);
                    XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = dataContext };
                    DataSoursModel dataSoursModel = xmlUtilCommon.GetXMLByDataModelBackID(confirmdocumenttemp);
                    DataModel evidemodel = dataContext.DataLayerOpt.SourdatModleList.FirstOrDefault(a => a.ID == evid);
                    List<DataModel> modelist = xmlUtilCommon.SubordinateDataModelList(dataContext.DataLayerOpt.SourdatModleList, evidemodel);
                    modelist.Remove(evidemodel);
                    dataSoursModel.dataModelList.FirstOrDefault(a => a.ParentId == "").ParentId = evidemodel.ID;
                    foreach (var item in modelist)
                    {
                        dataContext.DataLayerOpt.SourdatModleList.Remove(item);
                    }
                    dataContext.DataLayerOpt.SourdatModleList.AddRange(dataSoursModel.dataModelList);
                    XmlDocument xmlDocument = xmlUtilCommon.DataModelByXml(dataContext.DataLayerOpt.SourdatModleList, "");
                }
            }
            catch (Exception)
            {
                dataContext.InteractiveShow.LogShow("证据要素合并失败");
            }
        }

        /// <summary>
        /// 获取同节点配置
        /// </summary>
        /// <returns></returns>
        private SameNodeConfig GetSameNodeConfig()
        {
            var configModel = dataContext.DataLayerSys.GetConfigModel(ModuleName);
            SameNodeConfig sameNodeConfig = new SameNodeConfig();
            if (dataContext.DataLayerAns.CaseCausesList.Count > 0)
            {
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(configModel.ConfigContent);
                XmlNode xmlNode = xmlDocument.SelectSingleNode("/root/step[@code='samenodejudge']");
                if (xmlNode != null)
                {
                    Dictionary<string, string> dicElement = new Dictionary<string, string>();
                    string url = xmlNode.Attributes["executefile"].Value;
                    url = url.Replace("{casetype}", dataContext.DataLayerAns.CaseType).Replace("{causecode}", dataContext.DataLayerAns.CaseCausesList[0].CC_ID);
                    dicElement.Add("fileFullName", url);
                    string elementMessage = WebUtil.DoGet(ConfigRetrieval.GetConfigRetrieval.GetAppSettingString("systemapi") + "/api/WordParse/GetConfigFileContent", dicElement, "utf-8");
                    dynamic elementcofig = JsonConvert.DeserializeObject<dynamic>(elementMessage);
                    if (elementcofig.result.code.ToString() == "1")
                    {
                        string elementcofigstr = elementcofig.body;
                        sameNodeConfig = XmlUtility.DeserializeToObject<SameNodeConfig>(elementcofigstr);
                    }

                }
            }
            return sameNodeConfig;
        }

        public string  EvidElment(DataModel dataModel,out XmlNode nodeEvide) 
        {
            string id = "";
            
            XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = dataContext };
            List<DataModel> dataModelEvideList = xmlUtilCommon.SubordinateDataModelList(dataContext.DataLayerOpt.SourdatModleList, dataModel);
            XmlDocument xmlDocEvide = XmlUtility.DataModelByXml(dataModelEvideList, dataModel.ParentId);
            if (xmlDocEvide.SelectSingleNode("//案由要素")!=null)
            {
                nodeEvide = xmlDocEvide.SelectSingleNode("//案由要素").ParentNode;
                if (nodeEvide != null)
                {
                    if (nodeEvide.Attributes["id"] != null)
                    {
                        id = nodeEvide.Attributes["id"].Value;
                    }

                }
            }
            else
            {
                nodeEvide = null;
            }
           

            return id;
        }

        /// <summary>
        /// 添加属性问题
        /// </summary>
        /// <param name="dataModel">节点</param>
        /// <param name="attname">属性名称</param>
        public void SetATTDataModel(DataModel dataModel, string attname,string attrVal)
        {
            if (dataModel.AttributesList.FirstOrDefault(a => a.Name == attname) != null)
            {
                dataModel.AttributesList.FirstOrDefault(a => a.Name == attname).sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue = attrVal;
            }
            else
            {
                AttributeInfo attributeInfo = new AttributeInfo();
                attributeInfo.Name = attname;
                Source source = new Source();
                source.SaveValue = attrVal;
                source.SourceCode = dataContext.DataLayerAns.SourceCode;
                source.IsCheck = "1";
                attributeInfo.sourceList = new List<Source>();
                attributeInfo.sourceList.Add(source);
                dataModel.AttributesList.Add(attributeInfo);
            }
        }

        /// <summary>
        /// 调用推导进行获取数据
        /// </summary>
        public void Deduction(DataModel entityData)
        {
            DataDeduceDetail dataDeduceDetail = new DataDeduceDetail(dataContext, ModuleName);
            Dictionary<string, List<string>> re = dataDeduceDetail.GetDeduceResult(GetDeduceParameter(), "EvidElementXml", "wordparse", "po");
            UpdateXml(re,entityData);
        }
        
        /// <summary>
        /// 填充数据值
        /// </summary>
        public void UpdateXml(Dictionary<string, List<string>> result,DataModel entityData)
        {
            if (result==null && result.Count==0)
            {
                //返回为空，或者数据量为0则无法匹配
                return;
            }
            else
            {
                //进行ID赋值
                foreach (var kv in result)
                {
                    foreach (var value in kv.Value)
                    {
                        #region 将Jarray转到类中
                        DeduceResultList resultList = new DeduceResultList();
                        resultList.DeduceOutResult = new List<DeduceResultModel>();
                        JArray ja = (JArray)JsonConvert.DeserializeObject(value);
                        foreach (var jToken in ja)
                        {
                            JObject jo = (JObject)jToken;
                            DeduceResultModel joModel = JsonConvert.DeserializeObject<DeduceResultModel>(jo.ToString());
                            resultList.DeduceOutResult.Add(joModel);
                        }
                        #endregion
                        // 获取每条规则执行后的结果集合List<一条规则执行后的结果>
                        List<List<ElementOutVo>> deduceResult = resultList.DeduceOutResult.Select(a => a.Result).ToList();
                        foreach (List<ElementOutVo> item in deduceResult)
                        {
                            if (item.FirstOrDefault(a=> a.Name.ToLower()=="id")!=null)
                            {
                                var resul = item.FirstOrDefault(a => a.Name.ToLower() == "id");
                                DataModel dataRootModel=dataContext.DataLayerOpt.SourdatModleList.FirstOrDefault(a => a.ID == resul.OperateResult);
                                if (dataRootModel != null)
                                {
                                    var entitySfid = entityData.AttributesList.FirstOrDefault(x => x.Name == "证据文件ID")?.sourceList?.FirstOrDefault(a => a.IsCheck == "1")?.SaveValue;
                                    if (!string.IsNullOrWhiteSpace(entitySfid))
                                        SetATTDataModel(dataRootModel, "证据文件ID", entitySfid);
                                    var entityType = entityData.AttributesList.FirstOrDefault(x => x.Name == "证据类型")?.sourceList?.FirstOrDefault(a => a.IsCheck == "1")?.SaveValue;
                                    if (!string.IsNullOrWhiteSpace(entityType))
                                        SetATTDataModel(dataRootModel, "证据类型", entityType);
                                    var entityClass = entityData.AttributesList.FirstOrDefault(x => x.Name == "证据分类")?.sourceList?.FirstOrDefault(a => a.IsCheck == "1")?.SaveValue;
                                    if (!string.IsNullOrWhiteSpace(entityClass))
                                        SetATTDataModel(dataRootModel, "证据分类", entityClass);
                                    var entitySourceCode = entityData.AttributesList.FirstOrDefault(x => x.Name == "证据文书编号")?.sourceList?.FirstOrDefault(a => a.IsCheck == "1")?.SaveValue;
                                    if (!string.IsNullOrWhiteSpace(entitySourceCode))
                                        SetATTDataModel(dataRootModel, "证据文书编号", entitySourceCode);
                                    var entitySourceName = entityData.AttributesList.FirstOrDefault(x => x.Name == "标准名称")?.sourceList?.FirstOrDefault(a => a.IsCheck == "1")?.SaveValue;
                                    if (!string.IsNullOrWhiteSpace(entitySourceName))
                                        SetATTDataModel(dataRootModel, "标准名称", entitySourceName);
                                }
                            }
                        }

                    }
                }
            }

        }
        
        /// <summary>
        /// 拼接参数
        /// </summary>
        /// <returns></returns>
        public DeduceInputModel GetDeduceParameter()
        {
            DeduceInputModel result = new DeduceInputModel();
            #region 组装参数
            try
            {
                result.code = "MSCaseDeduction";

                #region 添加参数
                result.outParameter = new List<OutParameterItem>();
                for (int i = 0; i < 7; i++)
                {
                    OutParameterItem outParameter = new OutParameterItem();
                    switch (i)
                    {
                        case 0:
                            outParameter.code = "CaseID";
                            outParameter.Value = dataContext.DataLayerAns?.CaseId;
                            break;
                        case 1:
                            outParameter.code = "CaseType";
                            outParameter.Value = dataContext.DataLayerAns?.CaseType;
                            break;
                        case 2:
                            outParameter.code = "CaseCauseID";
                            if (dataContext.DataLayerAns.CaseCausesList != null && dataContext.DataLayerAns.CaseCausesList.Count > 0)
                            {
                                outParameter.Value = dataContext.DataLayerAns.CaseCausesList[0]?.CC_ID;
                            }
                            break;
                        case 3:
                            outParameter.code = "OutRelatID";
                            outParameter.Value = dataContext.DataLayerAns.Shujuneirong?.Shujuid;
                            break;
                        case 4:
                            outParameter.code = "CaseElementXml";
                            outParameter.Type = "base64";
                            string dd = dataContext.DataLayerOpt?.OptimizationXml?.OuterXml;
                            if (!string.IsNullOrWhiteSpace(dd))
                                outParameter.Value = HttpHelp.EnDataBase64(dd);
                            break;
                        case 5:
                            outParameter.code = "EvidElementXml";
                            outParameter.Type = "base64";
                            string edd = "";
                            if (dataContext.DataLayerAns.AnalysisResultsXml!=null)
                            {
                                edd = dataContext.DataLayerAns.AnalysisResultsXml.OuterXml;
                            }
                           
                            if (!string.IsNullOrWhiteSpace(edd))
                                outParameter.Value = HttpHelp.EnDataBase64(edd);
                            break;
                        case 6:
                            if(!string.IsNullOrWhiteSpace(dataContext.DataLayerAns.District))
                            {
                                outParameter.code = "District";
                                outParameter.Type = "String";
                                outParameter.Value = dataContext.DataLayerAns?.District;
                            }
                            break;
                        default:
                            break;
                    }
                    result.outParameter.Add(outParameter);
                }
                #endregion
            }
            catch (System.Exception ex)
            {
                dataContext.InteractiveShow.LogShow("********************对接推导服务GetDeduceParameter发生错误:" + ex.Message.ToString(), LogMessageType.Error);
            }
            #endregion

            return result;
        }
    }
}
